import OLCesium from 'olcs/OLCesium.js';
import olSourceOSM from 'ol/source/OSM.js';
import olSourceXYZ from 'ol/source/XYZ.js';
import olLayerTile from 'ol/layer/Tile.js';
import olMap from 'ol/Map.js';
import {transform} from 'ol/proj.js';
import olView from 'ol/View.js';
import {OLCS_ION_TOKEN} from './_common.js';

// 在文件开头检查 Cesium 是否可用
if (typeof Cesium === 'undefined') {
  throw new Error('Cesium is not available. Make sure it is loaded before this script.');
}

const view = new olView({
  center: transform([25, 20], 'EPSG:4326', 'EPSG:3857'),
  zoom: 3,
  rotation: Math.PI / 6
});

Cesium.Ion.defaultAccessToken = OLCS_ION_TOKEN;
const ol2d = new olMap({
  layers: [
    new olLayerTile({
      source: new olSourceXYZ({
        url: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
      })
    })
  ],
  target: 'map2d',
  view
});

const ol3d = new OLCesium({map: ol2d, target: 'map3d'});
const scene = ol3d.getCesiumScene();

// 使用通过 olcs 导出的 GeoTerrainProvider
const GeoTerrainProvider = window.olcs?.tdt?.GeoTerrainProvider;

if (!GeoTerrainProvider) {
  console.error('GeoTerrainProvider not found in olcs.tdt');
  // 回退到 EllipsoidTerrainProvider
  scene.terrainProvider = new Cesium.EllipsoidTerrainProvider();
} else {
  scene.terrainProvider = new GeoTerrainProvider({
    url: 'https://t{s}.tianditu.gov.cn/mapservice/swdx?T=elv_c&x={x}&y={y}&l={z}&tk=a71bfa9157d1eb20dcc39ec7bbbaeb9a',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
  });
}

scene._creditContainer.style.display = "none";
ol3d.setEnabled(true);

document.getElementById('enable').addEventListener('click', () => ol3d.setEnabled(!ol3d.getEnabled()));
